<template>
  <div class="homebox" :style="{ backgroundImage: 'url(' + BgImg + ')' }">
    <div class="wrapper-box">
      <div class="loginBox">
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
        >
          <h2 class="title">账号登录</h2>
          <el-form-item prop="phone">
            <el-input placeholder="手机号" v-model="loginForm.phone" clearable class="elItem">
              <img slot="prefix" src="@/assets/icon/phone.png" alt="" />
            </el-input>
          </el-form-item>
          <el-form-item prop="code">
            <el-input
              placeholder="验证码"
              v-model="loginForm.code"
              class="code elItem"
            >
              <img slot="prefix" src="@/assets/icon/code.png" alt="" />
              <span
                slot="suffix"
                @click="canClick && getCode()"
                class="getCode"
                >{{ canClick ? codeText : countNum }}</span
              >
            </el-input>
          </el-form-item>
          <div class="actionBtn">
            <el-button
              class="thirdparty-button"
              type="primary"
              @click="submitForm()"
            >
              登录
            </el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import Cookies from 'js-cookie'
import { regPhone } from "@/utils/validate";
import { Form as ElForm, Input } from "element-ui";
import loginApi from "@/APIService/api/login";
import { setToken } from "@/utils/cookies";
import {supplayMenu,adminMenu} from '@/utils/common'
import router from '../router'

@Component({
  name: "login",
})
export default class extends Vue {
  // 默认规则
   MenuList:any  = [] // 初始化 空数组
   supplayMenu= supplayMenu
   adminMenu = adminMenu
  private regPhoneTest = (rule: any, value: string, callback: any) => {
    if (value) {
      regPhone(value, callback);
    }
  };

  BgImg: string = require("@/assets/bg.jpg")
  total:number = 0
  canClick: boolean = true
  codeText: string = "获取验证码"
  countNum: number = 60
  timer: any = null
  token: string = ""
  private loginForm = {
    phone: "",
    code: ""
  }
  private loginRules = {
    phone: [{ validator: this.regPhoneTest, trigger: "blur" }],
    code: [{ required: true, message: "请输入验证码", trigger: "change" }],
  }

  // methods
  private async getCode() {
    // 先判断phone
    if (!this.loginForm.phone) {
      this.$message.warning("请输入手机号");
      return;
    }
    // 输入正确的手机号开始倒计时
    let phone = this.loginForm.phone;
    let res = await loginApi.sendCode({ phone });
    if (res.code === 20000) {
      this.$message.success("发送成功");
      this.canClick = false;
      this.timer = setInterval(() => {
        this.countNum--;
        if (this.countNum === 0) {
          this.canClick = true;
          clearInterval(this.timer);
        }
      }, 1000);
    } else {
      this.$message.error(res.msg);
    }
  }
  private async submitForm() {
    (this.$refs.loginForm as ElForm).validate((valid: boolean) => {
      if (valid) {
        // 校验code
        loginApi
          .checkCode({
            phone: this.loginForm.phone,
            code: this.loginForm.code,
            role: "USER",
          })
          .then((res) => {
            if (res.code === 20000) {
              loginApi
                .login({
                  phone: this.loginForm.phone,
                  captcha: this.loginForm.code,
                  source: "pc",
                  type: "phone",
                })
                .then((res) => {
                  if (res.code === 20000) {
                    this.token = res.data.token;
                    setToken(this.token)
                     Cookies.set('token',this.token)
                    this.getUserInfo()
                  }
                });
            } else {
              this.$message.error(res.msg);
            }
          })
      } else {
        console.log("error submit!!");
        return false;
      }
    })
  }

  async getUserInfo() {
    let res = await loginApi.getInfo();
    if (res.code === 20000) {
      sessionStorage.setItem("userInfo", JSON.stringify(res.data))
      this.$store.commit('updateUserInfo',res.data)
      const role = res.data.role
    
      if(role === 'SUPPLIER'){
        this.MenuList = this.supplayMenu
      }
      else{
        this.MenuList = this.adminMenu
      }
     
      router.addRoutes(this.MenuList)
      this.$store.commit('addMenuList', this.MenuList)
      role === 'SUPPLIER'?this.$router.push('/approval'): this.$router.push('/')
     
    } else {
      this.$message.error(res.msg);
    }
  }
}
</script>

<style scoped>
.elItem>>>.el-input__inner {
     border: none;
    border-bottom: 1px solid #ccc;
    height: 56px;
    line-height: 56px;
    padding-left: 45px;
   
}

</style>

<style lang="less" scoped>
.homebox {
  height: 100%;
  width: 100%;
  background-size: cover;
  position: absolute; /* 不可缺少 */
  z-index: -1;
  background-repeat: no-repeat;
  .wrapper-box {
    display: flex;
    justify-content: flex-end;
  }

  .loginBox {
    width: 360px;
    height: 400px;
    padding: 0 36px;
    background: #fff;

    margin-top: 50vh;
    transform: translateY(-50%);

    box-shadow: 0 0 10px gray;
    .title {
      color: #1677ff;
      text-align: center;
      margin: 40px 0 30px 0;
    }
    .getCode {
      color: #1677ff;
      border-left: 1px solid #ccc;
      padding: 5px 0 5px 15px;
    }
    .actionBtn {
      display: flex;
      justify-content: center;
      margin-top: 30px;
    }
  }
}
</style>